from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.db import connection
from django.db.models import Q
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.urls import reverse
from apps.courses.models import Courses
from apps.homework.models import HomeWork, UserHomeWork
from apps.operation.models import UserFavorite, UserMessage, CourseDiscussComment
from apps.organization.models import Teacher, CourseOrg
from apps.users.forms import LoginForm, DynamicLoginForm, DynamicLoginPostForm, RegisterGetForm, RegisterPostForm, \
    UploadImageForm, UserInfoForm, ChangePwdForm, UpdateMobileForm
from apps.users.models import UserProfile
from apps.utils.redis_utitls import setRedisCode, getRedisCode
from apps.utils.send_code import send_code
from apps.utils.random_str import generate_random


class MyDiscussListDeatilView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        coursediscuss_id = request.GET.get("discuss_id", "")
        print(coursediscuss_id)
        sql = '''
        SELECT  `users_userprofile`.`nick_name`,`users_userprofile`.`username`,t.discuss_count,t.coursediscuss_id 
        FROM `courses_coursediscuss` JOIN 
         (SELECT user_id,COUNT(coursediscuss_id) discuss_count ,coursediscuss_id
          FROM `operation_coursediscusscomment` GROUP BY user_id,coursediscuss_id  ) AS t
          ON `courses_coursediscuss`.`id`=t.coursediscuss_id 
          JOIN `users_userprofile` ON t.user_id=`users_userprofile`.`id`
        WHERE coursediscuss_id =%s
    '''

        with connection.cursor() as cursor:
            cursor.execute(sql, coursediscuss_id)
            discuss_result = cursor.fetchall()
        print(discuss_result)



        paginator = Paginator(discuss_result, 10)
        try:
            page = request.GET.get('page',1)
        except Exception:
            page = 1
        result_obj = paginator.get_page(page)
        page_obj = {
            "current_page":result_obj.number,
            "page_num":paginator.num_pages,
            "has_pre":result_obj.has_previous(),
            "has_next":result_obj.has_next(),
        }
        print(page_obj)
        if result_obj.has_previous():
            print("有上一页")
            page_obj["pre_num"] = result_obj.previous_page_number()
        else:
            page_obj["pre_num"] =1
        if result_obj.has_next():
            print("有下一页")
            page_obj["next_num"] = result_obj.next_page_number()
        else:
            page_obj["next_num"] =result_obj.number
        print(page_obj)
        # page_obj["bbb"]=result_obj.next_page_number() if result_obj.next_page_number() else result_obj.number
        # "pre_num": result_obj.previous_page_number() if result_obj.has_previous() else 1,
        # "next_num": result_obj.next_page_number() if result_obj.next_page_number() else result_obj.number

        result = []
        i = 1
        for item in result_obj:
            data={}
            print(item)

            data["id"]=i
            data["nickname"]=item[0]
            data["username"]=item[1]
            data["discusscount"]=item[2]

            result.append(data)
            i = i + 1
        print(result)
        # , "page_obj": page_obj
        return JsonResponse({"data":result,"page_obj":page_obj},json_dumps_params={"ensure_ascii":False})


'''话题讨论人数统计'''


class MyDiscussListView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_grade_classfication"
        teacher = Teacher.objects.filter(user=request.user).first()
        teach_course_list = []
        if teacher:
            teach_course_list = teacher.teacher_course().order_by('name')
        print(teach_course_list)

        paginator = Paginator(teach_course_list, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        teach_course_list = paginator.get_page(page)

        return render(request, "usercnter_discuss_list.html",
                      {"current_page": current_page, "teach_course_list": teach_course_list})


'''作业成绩表格展示  my_score_list'''


class MyScoreListView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_grade_classfication"
        teacher = Teacher.objects.filter(user=request.user).first()
        teach_course_list = []
        if teacher:
            teach_course_list = teacher.teacher_course().order_by('name')
        print(teach_course_list)
        homework_list = []
        user_score_list = []
        homework_id = request.GET.get("id", "")
        print(homework_id)
        course_info = {}
        for course in teach_course_list:
            for homework in course.home_work_all():
                homework_list.append(homework)
                user_score = {}
                for user_homework in homework.user_home_all():
                    if str(user_homework.homework_id) == homework_id:
                        user_score['id'] = user_homework.id
                        user_score["user"] = user_homework.user
                        user_score["score"] = user_homework.score
                        user_score["addtime"] = user_homework.add_time
                        course_info["coursename"] = course.name
                        course_info["homeworkname"] = user_homework.homework.name
                        user_score_list.append(user_score)
                        user_score = {}
        if homework_id == "":
            paginator = Paginator(homework_list, 5)
            try:
                page = request.GET.get('page', 1)
            except Exception:
                page = 1

            homework_list = paginator.get_page(page)
            # print(homework_list.)
            return render(request, 'usercnter_score_list.html',
                          {"current_page": current_page, "homework_list": homework_list})
        else:
            print(user_score_list)
            paginator = Paginator(user_score_list, 5)
            try:
                page = request.GET.get('page', 1)
            except Exception:
                page = 1
            user_score_list = paginator.get_page(page)
            # print(homework_list.)
            print(user_score_list)
            print(course_info)
            data = {
                "id": homework_id,
                "courseinfo": course_info
            }
            return render(request, 'usercnter_score_detail.html',
                          {"current_page": current_page, "user_score_list": user_score_list, "data": data})


'''我的授课'''


class MyTeachCourseView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myteach"
        teacher = Teacher.objects.filter(user=request.user).first()
        teach_course_list = []
        if teacher:
            teach_course_list = teacher.teacher_course()
        # print(teacher)
        # print(teacher.teacher_course())

        paginator = Paginator(teach_course_list, 4)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        teach_course_list = paginator.get_page(page)

        return render(request, 'usercenter-myteachcourse.html',
                      {"current_page": current_page, "teach_course_list": teach_course_list})


# Create your views here.
'''话题讨论人数折线图'''


class MyDiscussChartView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_grade_classfication"

        sql = "SELECT `courses_coursediscuss`.id discuss_id ,title,course_id,t.discuss_num ,`courses_courses`.`name`  FROM `courses_coursediscuss`JOIN  (SELECT coursediscuss_id discuss_id,COUNT(user_id) discuss_num FROM `operation_coursediscusscomment` GROUP BY coursediscuss_id ) AS t ON `courses_coursediscuss`.`id`=t.discuss_id JOIN `courses_courses` ON `courses_coursediscuss`.`course_id`=`courses_courses`.`id`"
        with connection.cursor() as cursor:
            cursor.execute(sql)
            discuss_result = cursor.fetchall()
        print(discuss_result)
        info_dic = {}
        # 讲授课程的id
        teacher = Teacher.objects.filter(user=request.user).first()
        teach_course_list = []
        if teacher:
            teach_course_list = teacher.teacher_course()
        # 讲授课程的id
        teach_id = []
        if teach_course_list:
            for item in teach_course_list:
                teach_id.append(item.id)

        for item in discuss_result:
            temp_list = []
            info = {}
            if self.request.user.is_staff and item[2] in teach_id:
                for item_j in discuss_result:
                    if item[2] == item_j[2]:
                        temp_list.append({'value': item_j[3], 'name': item_j[1]})

                info["title"] = item[4]
                info["data"] = temp_list
                info_dic[item[2]] = info
            if self.request.user.is_superuser:
                for item_j in discuss_result:
                    if item[2] == item_j[2]:
                        temp_list.append({'value': item_j[3], 'name': item_j[1]})

                info["title"] = item[4]
                info["data"] = temp_list
                info_dic[item[2]] = info
        data_list = []
        for item in info_dic:
            print(info_dic[item])
            data_list.append(info_dic[item])

        paginator = Paginator(data_list, 1)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        data_list = paginator.get_page(page)

        return render(request, 'usercnter_discuss_chart.html', {"data": data_list, "current_page": current_page})


'''作业成绩分类绘制折线图'''


@method_decorator(csrf_exempt, name='dispatch')
class MyGradeClassificationView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        # self.request.user.is_superuser
        current_page = "my_grade_classfication"
        sql = "SELECT homework_id, SUM(CASE WHEN score BETWEEN 90 AND 100 THEN 1 ELSE 0 END) AS A,SUM(CASE WHEN score BETWEEN 80 AND 89 THEN 1 ELSE 0 END) AS B, SUM(CASE WHEN score BETWEEN 70 AND 79 THEN 1 ELSE 0 END) AS C, SUM(CASE WHEN score BETWEEN 60 AND 69 THEN 1 ELSE 0 END) AS D, SUM(CASE WHEN score<60 THEN 1 ELSE 0 END) AS E FROM `homework_userhomework` GROUP BY homework_id"
        with connection.cursor() as cursor:
            cursor.execute(sql)
            user_score_classfication = cursor.fetchall()

        score_dic = {}
        for score in user_score_classfication:
            # print(score)
            temp_list = []
            for i in range(len(score)):
                if i > 0:
                    temp_list.append(int(score[i]))
            # score[0]=temp_list
            score_dic[score[0]] = temp_list
        print(score_dic)
        teacher = Teacher.objects.filter(user=request.user).first()
        teach_course_list = []
        if teacher:
            teach_course_list = teacher.teacher_course()
        # 讲授课程的id
        teach_id = []
        if teach_course_list:
            for item in teach_course_list:
                print(item.id)
                teach_id.append(item.id)
        home_work_id_list = []
        for user_home_work in user_score_classfication:
            home_work_id_list.append(user_home_work[0])
        home_work_list = HomeWork.objects.filter(id__in=home_work_id_list)
        # print(home_work_list)
        info_dic = {}
        for item in home_work_list:
            # print(item.id,item,item.course.id)
            value_list = []
            if self.request.user.is_staff and item.course.id in teach_id:
                for home_work in home_work_list:
                    temp = item.course.name

                    if home_work.course.id == item.course.id:
                        value_list.append(str(home_work.id) + "_" + str(home_work.name))
                info_dic[temp] = value_list
            if self.request.user.is_superuser:
                for home_work in home_work_list:
                    temp = item.course.name
                    if home_work.course.id == item.course.id:
                        value_list.append(str(home_work.id) + "_" + str(home_work.name))
                info_dic[temp] = value_list

        print(info_dic)

        name_dic = {}
        id_dic = {}
        for key, value in zip(info_dic.keys(), info_dic.values()):
            id_list = []
            name_list = []
            for item in info_dic[key]:
                id_list.append(int(item.split("_")[0]))
                name_list.append(item.split("_")[1])
            id_dic[key] = id_list
            name_dic[key] = name_list
        print(id_dic)
        print(name_dic)

        data_list = []
        for key, value in zip(info_dic.keys(), info_dic.values()):
            data = []
            # print(key)
            for id, name in zip(id_dic[key], name_dic[key]):
                # print(item)
                data_dic = {
                    'name': name,
                    'type': 'bar',
                    'data': score_dic[id]
                }
                data.append(data_dic)
            info = {
                "text": key,
                "legend_data": name_dic[key],
                "series":
                    data
            }
            data_list.append(info)

        print(data_list)
        paginator = Paginator(data_list, 1)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        data_list = paginator.get_page(page)
        # print(data_list.text)
        for item in data_list:
            print(item)
        return render(request, "usercnter_homwork_chart.html", {"data": data_list, "current_page": current_page})


'''讨论成绩'''


class MyDisCussScoreView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_score"
        # user_discuss_score=request.user.discuss_score()
        # user_discuss=CourseDiscussComment.objects.raw("SELECT   @i:=@i+1 AS 'id',coursediscuss_id ,user_id USER ,SUM(score) score  FROM `operation_coursediscusscomment` GROUP BY  coursediscuss_id,user_id")
        # print(user_discuss_score)
        # print(user_discuss)
        # for item in user_discuss:
        #     print(item)

        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT `organization_teacher`.`name` AS teacher_name, `courses_courses`.`name`,`courses_coursediscuss`.`course_id`,`courses_coursediscuss`.`add_time`,t.coursediscuss_id,`courses_coursediscuss`.`title` ,t.user_id,t.score,t.comments_count*0.1 AS  empiric_value FROM `courses_coursediscuss`JOIN  ( SELECT coursediscuss_id,user_id,SUM(score) AS score,COUNT(comments) AS comments_count FROM `operation_coursediscusscomment` WHERE user_id =%s GROUP BY coursediscuss_id,user_id ) AS t  ON `courses_coursediscuss`.`id`=t.coursediscuss_id JOIN `courses_courses` ON  `courses_coursediscuss`.`course_id`=`courses_courses`.`id` JOIN `organization_teacher` ON  `organization_teacher`.`id` =`courses_courses`.`teacher_id`",
                request.user.id)
            user_discuss_score = cursor.fetchall()
            print(user_discuss_score)
            # print()
        # for item in user_discuss_score:
        #     print(item)

        paginator = Paginator(user_discuss_score, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        user_discuss_score = paginator.get_page(page)
        return render(request, 'usercenter_discuss_score.html',
                      {'current_page': current_page, "user_discuss_score": user_discuss_score})


'''我的作业成绩'''


class MyScoreView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_score"
        user_score = request.user.home_work_score()

        paginator = Paginator(user_score, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        user_score = paginator.get_page(page)
        return render(request, 'usercenter-score.html', {'current_page': current_page, "user_score": user_score})


'''我的作业'''

'''        # 获取收藏状态
        has_fav_course = False
        has_fav_org = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course.id, fav_type=1):
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2):
                has_fav_org = True
'''


class MyHomeWorkView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "my_homework"
        user_course_id = request.user.usercourse_set.values_list('course')
        user_course_list = Courses.objects.filter(id__in=user_course_id)

        # print(user_course_list)
        myhomework = []
        for course in user_course_list:
            # Courses.objects.get()
            if course.home_work_all():
                # print(course.home_work_all())
                for work in course.home_work_all():
                    myhomework.append(work)

        paginator = Paginator(myhomework, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        myhomework = paginator.get_page(page)
        return render(request, 'usercenter-homework.html', {"current_page": current_page, 'myhomework': myhomework})

    def post(self, request, *args, **kwargs):
        # 上传作业
        work = request.POST.get('work_id')
        work_id = work.split('_')[0]
        page = work.split('_')[1]
        file = request.FILES.get('file')
        homework = HomeWork.objects.filter(id=work_id).first()
        userhomework = UserHomeWork()
        userhomework.user = request.user
        userhomework.homework = homework
        userhomework.submit_work = file
        userhomework.save()
        print(request.POST)
        print(request.FILES)
        return HttpResponseRedirect("/users/my_homework/?page=" + page)


'''
自定义用户验证逻辑
'''


class CustomAuth(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


'''未读消息数量'''


def message_nums(request):
    """
    Add media-related context variables to the context.
    """
    if request.user.is_authenticated:
        return {'unread_nums': request.user.usermessage_set.filter(has_read=False).count()}
    else:
        return {}


'''消息'''


class MyMessageView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):

        current_page = "message"
        messages = UserMessage.objects.filter(user=request.user).order_by('-add_time')
        for message in messages:
            message.has_read = True
            message.save()
            # 分页
        paginator = Paginator(messages, 5)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        messages = paginator.get_page(page)
        return render(request, "usercenter-message.html", {"messages": messages, "current_page": current_page})


'''收藏课程'''


class MyFavCourseView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfav_course"
        course_list = []
        fav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
        for fav_course in fav_courses:
            try:
                course = Courses.objects.get(id=fav_course.fav_id)
                course_list.append(course)
            except Courses.DoesNotExist as e:
                pass
        paginator = Paginator(course_list, 4)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        course_list = paginator.get_page(page)
        return render(request, "usercenter-fav-course.html", {
            "course_list": course_list,
            "current_page": current_page
        })


'''收藏老师'''


class MyFavTeacherView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfav_teacher"
        teacher_list = []
        fav_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
        for fav_teacher in fav_teachers:
            org = Teacher.objects.get(id=fav_teacher.fav_id)
            teacher_list.append(org)
        paginator = Paginator(teacher_list, 3)
        try:
            page = request.GET.get('page', '')
        except Exception:
            page = 1
        teacher_list = paginator.get_page(page)
        return render(request, "usercenter-fav-teacher.html", {
            "teacher_list": teacher_list,
            "current_page": current_page
        })


'''收藏机构'''


class MyFavOrgView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "myfavorg"
        org_list = []
        fav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
        for fav_org in fav_orgs:
            org = CourseOrg.objects.get(id=fav_org.fav_id)
            org_list.append(org)
        paginator = Paginator(org_list, 4)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        org_list = paginator.get_page(page)
        return render(request, "usercenter-fav-org.html", {
            "org_list": org_list,
            "current_page": current_page
        })


'''我的课程'''


class MyCourse(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "mycourse"
        user_course_list = request.user.usercourse_set.all().order_by('-add_time')
        paginator = Paginator(user_course_list, 4)
        try:
            page = request.GET.get('page', 1)
        except Exception:
            page = 1
        user_course_list = paginator.get_page(page)

        return render(request, 'usercenter-mycourse.html',
                      {"current_page": current_page, "user_course_list": user_course_list})


'''修改手机号'''


class ChangeMobileView(LoginRequiredMixin, View):
    login_url = "/login/"

    def post(self, request, *args, **kwargs):
        print(request.POST)
        mobile_form = UpdateMobileForm(request.POST)
        if mobile_form.is_valid():
            mobile = mobile_form.cleaned_data["mobile"]
            # 已经存在的记录不能重复注册
            # if request.user.mobile == mobile:
            #     return JsonResponse({
            #         "mobile": "和当前号码一致"
            #     })
            if UserProfile.objects.filter(mobile=mobile):
                return JsonResponse({
                    "mobile": "该手机号码已经被占用"
                })
            user = request.user
            user.mobile = mobile
            user.username = mobile
            user.save()
            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse(mobile_form.errors)


'''修改密码'''


class ChangePwdView(LoginRequiredMixin, View):
    login_url = "/login/"

    def post(self, request, *args, **kwargs):
        print(request.POST)
        pwd_form = ChangePwdForm(request.POST)
        if pwd_form.is_valid():
            pwd1 = request.POST.get("password1", "")
            user = request.user
            user.set_password(pwd1)
            user.save()
            # 修改密码之后会退出
            # login(request, user)

            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse(pwd_form.errors)


'''修改用户头像'''


class UploadImageView(LoginRequiredMixin, View):
    login_url = "/login/"

    def post(self, request, *args, **kwargs):
        # 处理用户上传的头像
        image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()
            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse({
                "status": "fail"
            })


'''个人中心'''


class UserInfoView(LoginRequiredMixin, View):
    login_url = "/login/"

    def get(self, request, *args, **kwargs):
        current_page = "info"
        captcha_form = RegisterGetForm()
        return render(request, "usercenter-info.html", {
            "captcha_form": captcha_form,
            "current_page": current_page
        })

    #
    def post(self, request, *args, **kwargs):
        user_info_form = UserInfoForm(request.POST, instance=request.user)
        if user_info_form.is_valid():
            user_info_form.save()
            return JsonResponse({
                "status": "success"
            })
        else:
            return JsonResponse(user_info_form.errors)


# 注册
class RegisterView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        # loginform = DynamicLoginForm()
        # {"login_form": loginform}
        register_get_form = RegisterGetForm()
        return render(request, "register.html", {"register_get_form": register_get_form})

    def post(self, request, *args, **kwargs):
        register_post_form = RegisterPostForm(request.POST)
        if register_post_form.is_valid():
            mobile = register_post_form.cleaned_data["mobile"]
            password = register_post_form.cleaned_data["password"]
            email = register_post_form.cleaned_data["email"]
            # 新建一个用户
            user = UserProfile(username=mobile)

            user.email = email
            user.set_password(password)
            user.mobile = mobile
            user.save()
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            register_get_form = RegisterGetForm()
            print(register_get_form.errors)
            return render(request, "register.html", {
                "register_post_form": register_post_form,
                "register_get_form": register_get_form
            })


# 发送短信验证码
class SendSmsView(View):
    def post(self, requests, *args, **kwargs):
        sms_form = DynamicLoginForm(requests.POST)
        print(requests.POST)
        res_dict = {}
        if sms_form.is_valid():
            eamil = sms_form.cleaned_data["email"]
            code = generate_random(4, 0)
            send_status = send_code(eamil, code)
            if send_status:
                res_dict["code"] = 0
                res_dict["status"] = "success"
                res_dict["msg"] = "邮件发送成功"
                # 5分钟过期
                setRedisCode(eamil, str(code), 60 * 5)
                print(getRedisCode(eamil))
            else:
                res_dict["code"] = 1
                res_dict["status"] = "fail"
                res_dict["msg"] = "邮件发送失败"
        else:
            print("失败")
            for key, value in sms_form.errors.items():
                res_dict[key] = value
        return JsonResponse(res_dict)


# 退出
class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(reverse("login"))


# 登录
class LoginView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        loginform = DynamicLoginForm()
        next = request.GET.get("next", "")
        return render(request, "login.html", {"login_form": loginform, "next": next})

    def post(self, request, *args, **kwargs):
        loginform = LoginForm(request.POST)
        print(loginform)
        # pass
        if loginform.is_valid():
            username = loginform.cleaned_data["username"]
            password = loginform.cleaned_data["password"]
            # username=request.POST.get("username","")
            # password=request.POST.get("password","")
            # if not all([username,password]):
            #     return  render(request,"login.html",{"msg":"用户名密码不能为空"})
            # print(username, password)
            # user = UserProfile.objects.filter(username=username, password=password)
            # print(user)
            # 内部方法查询到一个userprofile对象
            user = authenticate(username=username, password=password)
            print(user)
            # 内部登录方法
            if user:
                login(request, user)
                #     跳转出回页面
                next = request.GET.get("next", "")
                if next:
                    return HttpResponseRedirect(next)
                return HttpResponseRedirect(reverse("index"))
            else:
                d_form = DynamicLoginForm()
                return render(request, "login.html", {"msg": "用户名或密码错误", "loginform": loginform, "d_form": d_form})
        else:

            return render(request, "login.html", {"loginform": loginform})


# 验证码登录
class DynamicLoginView(View):
    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        loginform = DynamicLoginForm()
        next = request.GET.get("next", "")

        return render(request, "login.html", {"login_form": loginform, "next": next})

    def post(self, request, *args, **kwargs):
        loginform = DynamicLoginPostForm(request.POST)
        dynamic_login = True
        if loginform.is_valid():
            # 没有注册账号依然可以登录
            mobile = loginform.cleaned_data["mobile"]
            email_ = loginform.cleaned_data["email"]
            existed_users = UserProfile.objects.filter(mobile=mobile)
            if existed_users:
                user = existed_users[0]
            else:
                # 新建一个用户
                user = UserProfile(username=mobile, email=email_)
                password = generate_random(10, 2)
                user.set_password(password)
                user.mobile = mobile
                user.save()
            login(request, user)
            next = request.GET.get("next", "")
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect(reverse("index"))
            # return HttpResponseRedirect(reverse("index"))
        else:
            d_form = DynamicLoginForm()
            return render(request, "login.html",
                          {"loginform": loginform, "d_form": d_form, "dynamic_login": dynamic_login, })
